<script lang="ts" setup>
import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
import Banner from "@/components/Banner.vue"
import { ShoppingCart, Picture } from '@element-plus/icons-vue'

// 定义商品接口
interface Product {
  id: number
  name: string
  price: number
  stock: number
  img_url: string
  description: string
  create_date: string
}

// 定义首页需要的数据
let productList = reactive<Product[]>([
    {
        "id": 1,
        "name": "土豆丝",
        "price": 12,
        "stock": 50,
        "img_url": "土豆丝.jpg",
        "description": "经典家常菜，酸辣可口",
        "create_date": "2025-09-03 10:46:58"
    },
    {
        "id": 2,
        "name": "开水白菜",
        "price": 10,
        "stock": 45,
        "img_url": "开水白菜.jpg",
        "description": "川菜名品，清淡鲜美",
        "create_date": "2025-09-03 10:46:58"
    },
    {
        "id": 3,
        "name": "糖醋排骨",
        "price": 32,
        "stock": 60,
        "img_url": "糖醋排骨.jpg",
        "description": "酸甜可口，肉质鲜嫩",
        "create_date": "2025-09-03 10:46:58"
    },
    {
        "id": 4,
        "name": "红烧肉",
        "price": 50,
        "stock": 30,
        "img_url": "红烧肉.jpg",
        "description": "色泽红亮，肥而不腻",
        "create_date": "2025-09-03 10:46:58"
    },
    {
        "id": 5,
        "name": "西湖醋鱼",
        "price": 88,
        "stock": 55,
        "img_url": "西湖醋鱼.jpg",
        "description": "杭州名菜，酸甜鲜美",
        "create_date": "2025-09-03 10:46:58"
    },
    {
        "id": 6,
        "name": "西红柿炒鸡蛋",
        "price": 15,
        "stock": 40,
        "img_url": "西红柿炒鸡蛋.jpg",
        "description": "家常美味，营养丰富",
        "create_date": "2025-09-03 10:46:58"
    },
    {
        "id": 7,
        "name": "锅包肉",
        "price": 36,
        "stock": 35,
        "img_url": "锅包肉.jpg",
        "description": "东北名菜，外酥里嫩",
        "create_date": "2025-09-03 10:46:58"
    },
    {
        "id": 8,
        "name": "麻婆豆腐",
        "price": 11,
        "stock": 65,
        "img_url": "麻婆豆腐.jpg",
        "description": "麻辣鲜香，下饭神器",
        "create_date": "2025-09-03 10:46:58"
    },
])

// 添加到购物车功能
const addToCart = (product: Product) => {
  console.log('添加商品到购物车:', product.name)
  
  try {
    // 1. 获取现有购物车数据
    const existingCart = localStorage.getItem('cart')
    let cartItems = existingCart ? JSON.parse(existingCart) : []
    
    console.log('现有购物车数据:', cartItems)

    // 2. 检查商品是否已在购物车中
    const existingItemIndex = cartItems.findIndex((item: any) => item.id === product.id)
    
    if (existingItemIndex !== -1) {
      // 3. 如果商品已存在，增加数量
      cartItems[existingItemIndex].quantity++
      ElMessage.success(`已增加 ${product.name} 的数量`)
    } else {
      // 4. 如果商品不存在，添加到购物车
      const newCartItem = {
        id: product.id,
        name: product.name,
        price: product.price,
        quantity: 1,
        image: `/src/assets/images/${product.img_url}`,
        description: product.description
      }
      cartItems.push(newCartItem)
      ElMessage.success(`已添加 ${product.name} 到购物车`)
    }

    // 5. 保存更新后的购物车数据到localStorage
    localStorage.setItem('cart', JSON.stringify(cartItems))
    console.log('更新后的购物车数据已保存:', cartItems)

  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage.error('添加到购物车失败，请重试')
  }
}

// 查看购物车功能（调试用）
const viewCart = () => {
  const cart = localStorage.getItem('cart')
  const cartData = cart ? JSON.parse(cart) : '空'
  console.log('当前购物车内容:', cartData)
  ElMessage.info('请在控制台查看购物车数据')
}

// 清空购物车功能（调试用）
const clearCart = () => {
  localStorage.removeItem('cart')
  ElMessage.info('购物车已清空')
  console.log('购物车已清空')
}
</script>

<template>
  <Banner></Banner>
  
  <!-- 调试按钮 -->
  <div style="text-align: center; margin: 10px 0;">
    <el-button size="small" @click="viewCart" type="info" plain>
      查看购物车数据
    </el-button>
    <el-button size="small" @click="clearCart" type="danger" plain>
      清空购物车
    </el-button>
  </div>

  <!-- 使用Element Plus栅格系统 -->
  <el-row :gutter="20" justify="center" style="margin: 20px auto; max-width: 1200px;">
    <el-col 
      :xs="24"
      :sm="12"
      :md="8"
      :lg="6"
      :xl="6"
      v-for="p in productList" 
      :key="p.id"
      style="margin-bottom: 20px;"
    >
      <el-card class="product-card" shadow="hover">
        <!-- 商品图片 -->
        <el-image 
          :src="`/src/assets/images/${p.img_url}`" 
          :alt="p.name"
          style="height: 200px; width: 100%;"
          fit="cover"
        >
          <template #error>
            <div class="image-error">
              <el-icon><Picture /></el-icon>
              <span>图片加载失败</span>
            </div>
          </template>
        </el-image>

        <!-- 商品信息 -->
        <div style="padding: 15px;">
          <!-- 商品名称 -->
          <h3 style="margin: 0 0 10px 0; color: #333; text-align: center;">
            {{ p.name }}
          </h3>
          
          <!-- 价格和库存 -->
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
            <el-text type="danger" size="large" style="font-weight: bold;">
              ¥{{ p.price }}
            </el-text>
            <el-text type="info" size="small">
              库存: {{ p.stock }}
            </el-text>
          </div>

          <!-- 商品描述 -->
          <el-text 
            type="info" 
            size="small" 
            style="display: block; margin-bottom: 15px; line-height: 1.4; text-align: center;"
          >
            {{ p.description }}
          </el-text>

          <!-- 加入购物车按钮 -->
          <el-button 
            type="primary" 
            size="small" 
            @click="addToCart(p)"
            style="width: 100%;"
            :disabled="p.stock <= 0"
          >
            <template #icon>
              <el-icon><ShoppingCart /></el-icon>
            </template>
            {{ p.stock <= 0 ? '已售罄' : '加入购物车' }}
          </el-button>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<style scoped>
.product-card {
  border-radius: 12px;
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

.product-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  border-color: #409EFF;
  transform: translateY(-2px);
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  background: #f5f7fa;
  color: #909399;
}

.image-error .el-icon {
  font-size: 40px;
  margin-bottom: 8px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .el-col {
    padding: 0 10px;
  }
}

@media (max-width: 480px) {
  .product-card {
    margin: 0 5px;
  }
}
</style>